package image_cmds

import (
	"bufio"
	"fmt"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"github.com/spf13/cobra"
)

var pullCmd = &cobra.Command{
	Use: "pull",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 1 {
			return fmt.Errorf("need param [image]")
		}
		return nil
	},
	RunE: runPull,
}

func runPull(cmd *cobra.Command, args []string) error {
	cli, err := client.NewClientWithOpts(client.FromEnv)
	if err != nil {
		return err
	}
	resp, err := cli.ImagePull(cmd.Context(), args[0], types.ImagePullOptions{})
	if err != nil {
		return err
	}
	defer resp.Close()
	scanner := bufio.NewScanner(resp)
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}
	return nil
}
